#!/bin/bash

# Function to print an error message and exit
error_exit() {
    echo "Error: $1" >&2
    exit 1
}

# Check if the correct number of arguments is provided
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
    error_exit "Usage: $0 <url> <md5> [filename]"
fi

URL="$1"
MD5="$2"
FILENAME="$3"

# Extract filename from URL if not provided
if [ -z "$FILENAME" ]; then
    FILENAME=$(basename "$URL")
fi

# Create the target directory if it doesn't exist
TARGET_DIR="/firmware/Upgrade"
mkdir -p "$TARGET_DIR" || error_exit "Failed to create directory: $TARGET_DIR"

# Full path to the downloaded file
TARGET_FILE="$TARGET_DIR/$FILENAME"

# Function to download the file with retry logic
download_file() {
    while true; do
        echo "Downloading $URL to $TARGET_FILE..."
        curl -C - -o "$TARGET_FILE" "$URL" 2>&1 | \
            while read -r line; do
                echo "$line" | grep -o "([0-9.]\+%)"
            done
        if [ $? -eq 0 ]; then
            echo "Download completed successfully."
            break
        else
            echo "Download failed. Retrying in 5 seconds..."
            sleep 5
        fi
    done
}

# Download the file
download_file

# Verify the MD5 checksum
echo "Verifying MD5 checksum..."
echo "$MD5  $TARGET_FILE" | md5sum -c --status
if [ $? -eq 0 ]; then
    echo "MD5 checksum verified successfully."
    FILE_SIZE=$(stat -c%s "$TARGET_FILE")
    echo "Filename: $FILENAME"
    echo "File size: $FILE_SIZE bytes"
    echo "MD5: $MD5"
else
    error_exit "MD5 checksum verification failed."
fi

exit 0

